#Binary parser scions_mdllate

import os, sys
from Sanae3D.lib.ModelObject import Model3D
from Sanae3D.lib.StructReader import StructReader

class scions_mdl(Model3D):
    
    def __init__(self, obj3D=None, outFile=None, inFile=None):
        
        super(scions_mdl,self).__init__("XAC")
        self.obj3D = obj3D
        self.inFile = inFile
        self.outFile = outFile
        
    def parse_material(self, length):
        
        self.inFile.seek(68)
        texName = self.inFile.read_string(length + 4)
        print texName
        
        self.create_material(0)
        self.add_material_name(0, "mat1")
        self.add_texture_name(0, texName)
        
    def parse_file(self, filename):
        
        self.inFile.seek(0)
        header = self.inFile.read(4)
        if not header == "\xFF\xFF\xFF\xFF":
            self.inFile.seek(108)
            
            meshName = filename
            self.create_object(meshName)
            vertNum, faceNum = self.inFile.read_long(2)
            
            print "%d vertices, %d faces" %(vertNum, faceNum)
            
            for i in range(vertNum):
                vx, vy, vz = self.inFile.read_float(3)
                
                vx = float(vx) * -1
                
                self.inFile.read_float(3)
                self.inFile.read_float(2)
                
                self.create_vertex(meshName, i)
                self.add_coords(meshName, i, [vx, vy, vz])
                
            for i in range(faceNum):
                v1, v2, v3 = self.inFile.read_short(3)
                
                self.create_face(meshName, i)
                self.add_face_verts(meshName, i, [v1, v2, v3])
        
        
def read_file(path):
    
    openFile = StructReader(open(path, 'rb'))

    filename = os.path.splitext(os.path.basename(path))[0]
    
    obj = scions_mdl(inFile=openFile)
    obj.parse_material(len(filename))
    obj.parse_file(filename)
    openFile.close()
    return obj

if __name__ == '__main__':
    
    file1 = "ACS023.mdl"
    file2 = "WCA026.mdl"
    read_file(file2)